package com.cspg.ssss.service;

import com.alibaba.fastjson.JSONObject;
import com.cspg.ssss.domain.*;
import com.cspg.ssss.job.DailyJob;
import com.cspg.ssss.repository.*;
import com.cspg.ssss.util.DateUtil;
import com.cspg.ssss.vo.ProblemGradeViewVo;
import com.cspg.ssss.vo.convert.ProblemGradeViewVoConvert;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ProblemGradeService {

    private static final Logger log = LoggerFactory.getLogger(ProblemGradeService.class);

    @Autowired
    CheckBatchService checkBatchService;

    @Autowired
    GsdgdwGradeViewEntityMapper gsdgdwGradeViewEntityMapper;

    @Autowired
    GsdgdwGradeInfoEntityMapper gsdgdwGradeInfoEntityMapper;

    @Autowired
    DwdgbmGradeViewEntityMapper dwdgbmGradeViewEntityMapper;

    @Autowired
    DwdgbmGradeInfoEntityMapper dwdgbmGradeInfoEntityMapper;

    @Autowired
    CheckItemMapper checkItemMapper;

    @Autowired
    FeedbackService feedbackService;

    @Autowired
    ScoreAddApplyEntityMapper scoreAddApplyEntityMapper;

    public List<GsdgdwGradeViewEntity> getAllGsdgdwGradeView(){
        Map<String,Object> condition = new HashMap<String, Object>();
        return gsdgdwGradeViewEntityMapper.selectGsdgdwGradeView(condition);
    }

    @Transactional
    public String initCheckItem(String txtItem){
        Map<String,Object> condition = new HashMap<String, Object>();
        condition.put("item",txtItem);
        List<CheckItem> ls = checkItemMapper.selectCheckItem(condition);

        CheckItem it = null;

        if(ls != null && ls.size() == 1) {
           it  = ls.get(0);

        }else {
            it = new CheckItem();
            it.setId("35");
            it.setItem("无考核载体");
            it.setLevel(1);
        }

        JSONObject obj = new JSONObject();
        obj.put("id", it.getId());
        obj.put("item", it.getItem());
        JSONObject checkitemObj = new JSONObject();
        checkitemObj.put("id", "");
        checkitemObj.put("item", "");

        JSONObject scoreitemObj = new JSONObject();
        scoreitemObj.put("id", "");
        scoreitemObj.put("item", "");

        checkitemObj.put("score_item", scoreitemObj);

        obj.put("content_item", checkitemObj);
        String check_item = obj.toJSONString();
        return check_item;

    }

    public String syncGradeInfo(int check_type, Date start, Date end){
        CheckBatchInst batchInst = checkBatchService.getCurrentCheckBachInst(check_type);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String d=sdf1.format(start);
        String d1=sdf1.format(end);

        Map<String,Object> condition = new HashMap<String,Object>();
        condition.put("batchid",batchInst.getId());
        condition.put("startDate",d);
        condition.put("endDate",d1);

        if(check_type == 0){
            gsdgdwGradeInfoEntityMapper.syncGsdgdwGradeInfo(condition);
        }
        if(check_type == 1){
            dwdgbmGradeInfoEntityMapper.syncDwdgbmGradeInfo(condition);
        }

        return "success sync grade info";
    }

    /**
     * 分页获取问题评分列表
     * @param pageNum
     * @param pageSize
     * @param problem_type
     * @param condition
     * @return
     */
    public PageInfo<ProblemGradeViewVo> getProblemGradeViewByPageWithCondition(int pageNum, int pageSize,int problem_type,Map<String,Object> condition) {
        Page pg = (Page) PageHelper.startPage(pageNum, pageSize);
        List<ProblemGradeViewVo> retlist = new ArrayList<ProblemGradeViewVo>();

        if(problem_type == 0){
            List<GsdgdwGradeViewEntity> ls = gsdgdwGradeViewEntityMapper.selectGsdgdwGradeView(condition);
            retlist = ProblemGradeViewVoConvert.ConvertListGsdgdw(ls);
        }

        if(problem_type == 1){
            List<DwdgbmGradeViewEntity> ls = dwdgbmGradeViewEntityMapper.selectDwdgbmGradeView(condition);
            retlist = ProblemGradeViewVoConvert.ConvertListDwdgbm(ls);
        }

        PageInfo<ProblemGradeViewVo> pgInfo = new PageInfo<ProblemGradeViewVo>(retlist);
        pgInfo.setPageNum(pg.getPageNum());
        pgInfo.setPageSize(pg.getPageSize());
        pgInfo.setTotal(pg.getTotal());
        pgInfo.setPages(pg.getPages());

        return pgInfo;
    }

    /**
     * 分页获取问题评分列表
     * @param problem_type
     * @param condition
     * @return
     */
    public List<ProblemGradeViewVo> getProblemGradeViewAllWithCondition(int problem_type,Map<String,Object> condition) {

        List<ProblemGradeViewVo> retlist = new ArrayList<ProblemGradeViewVo>();

        if(problem_type == 0){
            List<GsdgdwGradeViewEntity> ls = gsdgdwGradeViewEntityMapper.selectGsdgdwGradeView(condition);
            retlist = ProblemGradeViewVoConvert.ConvertListGsdgdw(ls);
        }

        if(problem_type == 1){
            List<DwdgbmGradeViewEntity> ls = dwdgbmGradeViewEntityMapper.selectDwdgbmGradeView(condition);
            retlist = ProblemGradeViewVoConvert.ConvertListDwdgbm(ls);
        }

        return retlist;
    }

    public PageInfo<ProblemGradeViewVo> getProblemListWithApproveByPage(int pageNum, int pageSize,int problem_type,Map<String,Object> condition){
        Page pg = (Page) PageHelper.startPage(pageNum, pageSize);
        List<ProblemGradeViewVo> retlist = new ArrayList<ProblemGradeViewVo>();
        condition.put("ne_sscm","公司层面");
        if(problem_type == 0){
            List<GsdgdwGradeViewEntity> ls = gsdgdwGradeViewEntityMapper.selectProblemGradeListWithApproveUser(condition);
            retlist = ProblemGradeViewVoConvert.ConvertListGsdgdw(ls);
        }

        if(problem_type == 1){
            List<DwdgbmGradeViewEntity> ls = dwdgbmGradeViewEntityMapper.selectProblemGradeListWithApproveUser(condition);
            retlist = ProblemGradeViewVoConvert.ConvertListDwdgbm(ls);
        }

        PageInfo<ProblemGradeViewVo> pgInfo = new PageInfo<ProblemGradeViewVo>(retlist);
        pgInfo.setPageNum(pg.getPageNum());
        pgInfo.setPageSize(pg.getPageSize());
        pgInfo.setTotal(pg.getTotal());
        pgInfo.setPages(pg.getPages());
        return pgInfo;
    }
    /**
     * 根据条件统计某个状态的问题数量
     * @param condition
     * @return
     */
    public int getProblemCountByStatusWithCondition(int pType,Map<String,Object> condition){
        int cnt = 0;
        if(pType == 0){
            cnt = gsdgdwGradeViewEntityMapper.selectProblemGradeNumStat(condition);
        }
        if(pType == 1){
            cnt = dwdgbmGradeViewEntityMapper.selectProblemGradeNumStat(condition);
        }
        return cnt;
    }

    /**
     * 根据id和问题类型获取问题评分详情
     * @param id
     * @param ptype
     * @return
     */
    public ProblemGradeViewVo getProblemGradeViewDetail(String id,int ptype){

        ProblemGradeViewVo ret = null;

        Map<String,Object> condition = new HashMap<String,Object>();
        condition.put("id",id);
        if(ptype == 0){
            //先尝试更新check_item，在查询返回

            List<GsdgdwGradeViewEntity> ls = gsdgdwGradeViewEntityMapper.selectGsdgdwGradeView(condition);
            if(ls != null && ls.size() == 1){
                GsdgdwGradeViewEntity en = ls.get(0);
                if(ls.get(0).getProblem_status() == 0 || ls.get(0).getProblem_status() == 8) {
                    if (ls.get(0).getCheck_item() == null || ls.get(0).getCheck_item().equals("")) {
                        String str = initCheckItem(ls.get(0).getYwsx());
                        Map<String, Object> updatecondition = new HashMap<String, Object>();
                        updatecondition.put("id", id);
                        updatecondition.put("check_item", str);
                        gsdgdwGradeInfoEntityMapper.updateProblemGradeInfo(updatecondition);
                        en.setCheck_item(str);
                    } else {
                        JSONObject obj = JSONObject.parseObject(ls.get(0).getCheck_item());
                        if (ls.get(0).getYwsx().equalsIgnoreCase(obj.getString("item")) == false) {
                            String str = initCheckItem(ls.get(0).getYwsx());
                            Map<String, Object> updatecondition = new HashMap<String, Object>();
                            updatecondition.put("id", id);
                            updatecondition.put("check_item", str);
                            gsdgdwGradeInfoEntityMapper.updateProblemGradeInfo(updatecondition);
                            en.setCheck_item(str);
                        }
                    }
                }
                ret = ProblemGradeViewVoConvert.ConvertFromGsdgdw(en);
                ret.setProblem_type(ptype);
            }
        }

        if(ptype == 1){
            //先尝试更新check_item，在查询返回
            List<DwdgbmGradeViewEntity> ls = dwdgbmGradeViewEntityMapper.selectDwdgbmGradeView(condition);
            if(ls != null && ls.size() == 1){
                if(ls.get(0).getProblem_status() == 0 || ls.get(0).getProblem_status() == 8) {
                    if (ls.get(0).getCheck_item() == null || ls.get(0).getCheck_item().equals("")) {
                        String str = initCheckItem(ls.get(0).getYwsx());
                        Map<String, Object> updatecondition = new HashMap<String, Object>();
                        updatecondition.put("id", id);
                        updatecondition.put("check_item", str);
                        dwdgbmGradeInfoEntityMapper.updateProblemGradeInfo(updatecondition);
                        ls.get(0).setCheck_item(str);
                    } else {
                        JSONObject obj = JSONObject.parseObject(ls.get(0).getCheck_item());
                        if (ls.get(0).getYwsx().equalsIgnoreCase(obj.getString("item")) == false) {
                            String str = initCheckItem(ls.get(0).getYwsx());
                            Map<String, Object> updatecondition = new HashMap<String, Object>();
                            updatecondition.put("id", id);
                            updatecondition.put("check_item", str);
                            dwdgbmGradeInfoEntityMapper.updateProblemGradeInfo(updatecondition);
                            ls.get(0).setCheck_item(str);
                        }
                    }
                }

                ret = ProblemGradeViewVoConvert.ConvertFromDwdgbm(ls.get(0));
                ret.setProblem_type(ptype);
            }
        }

        return ret;
    }

    /**
     * 单个更新评分问题
     * @param check_type
     * @param condition
     */
    public void updateProblemGradeInfo(int check_type,Map<String,Object> condition){
        if(check_type == 0){
            gsdgdwGradeInfoEntityMapper.updateProblemGradeInfo(condition);
        }
        if(check_type == 1){
            dwdgbmGradeInfoEntityMapper.updateProblemGradeInfo(condition);
        }
    }

    /**
     * 评分情况统计，按照被考核单位或部门来分组统计
     * @param condition
     * @return
     */
    public List<GradeDeptStatEntity> getDeptGradeStat(int problem_type,Map<String,Object> condition){
        if(problem_type == 0){
            return gsdgdwGradeViewEntityMapper.selectProblemStatusNumDwmcStat(condition);
        }

        if(problem_type == 1){
            return dwdgbmGradeViewEntityMapper.selectProblemStatusNumBmmcStat(condition);
        }

        return null;
    }

    /**
     * 批量审核评分问题
     * @param problem_type
     * @param condition
     */
    public void batchApproveProblemGrade(int problem_type,Map<String,Object> condition){
        if(problem_type == 0){
            gsdgdwGradeInfoEntityMapper.batchApproveProblemGrade(condition);
        }

        if(problem_type == 1){
            dwdgbmGradeInfoEntityMapper.batchApproveProblemGrade(condition);
        }
    }

    /**
     * 统计查询，按照被考核部门打分情况进行统计 （被考核单位名称，待审核问题，总扣分数量，）
     * @param problem_type
     * @param condition
     * @return
     */
    public List<GradeDeptStatEntity> selectApproveProblemGradeStatusNumStat(int problem_type,Map<String,Object> condition){
        List<GradeDeptStatEntity> retls = new ArrayList<GradeDeptStatEntity>();

        if(problem_type == 0){
            retls = gsdgdwGradeViewEntityMapper.selectApproveProblemGradeStatusNumStat(condition);
        }

        if(problem_type == 1){
            retls = dwdgbmGradeViewEntityMapper.selectApproveProblemGradeStatusNumStat(condition);
        }

        return retls;
    }

    /**
     * 根据条件，统计不同评分状态的评分问题数量
     * @param problem_type
     * @param condition
     * @return
     */
    public List<StatusCountEntity> selectProblemGradeStatusNumStat(int problem_type,Map<String,Object> condition){
        List<StatusCountEntity> retls = new ArrayList<StatusCountEntity>();

        if(problem_type == 0){
            retls = gsdgdwGradeViewEntityMapper.selectProblemGradeStatusNumStat(condition);
        }

        if(problem_type == 1){
            retls = dwdgbmGradeViewEntityMapper.selectProblemGradeStatusNumStat(condition);
        }

        return retls;
    }

    /**
     * 判断并切换打分的阶段
     * @return -1-未切换，0，1，2，3-已切换到的阶段状态
     */
    public int setNextStage(int check_type){
        CheckBatchInst inst = checkBatchService.getCurrentCheckBachInst(check_type);
        if(inst == null)
            return -1;

        JSONObject configObj = JSONObject.parseObject(inst.getConfig());
        int upload_days = configObj.getIntValue("upload_problem");
        int grade_days = configObj.getIntValue("grade");
        int feedback_days = configObj.getIntValue("feedback");
        int review_days = configObj.getIntValue("review");
        int add_score_apply_days = configObj.getIntValue("add_score_apply");
        int add_score_review_days = configObj.getIntValue("add_score_review");
        Date today = DateUtil.getCurrentDate();
        int period = DateUtil.workDaysPeriod(inst.getUpdate_time(),today);

        if(inst.getCurrent_stage() == 0){//切换到打分反馈阶段

            //根据限定期限，强制切换阶段
            if(period > (upload_days+grade_days)){
                //设置所有该批次问题状态为2，所有状态不为2的问题，扣分结果为0
                Map<String,Object> updatefiled = new HashMap<String, Object>();

                updatefiled.put("problem_status",2);
                updatefiled.put("score","0");
                updatefiled.put("batch_id",inst.getId());
                List<Integer> statusls = new ArrayList<Integer>();
                statusls.add(0);
                statusls.add(1);
                updatefiled.put("w_problem_status_in",statusls);
                updateProblemGradeInfo(check_type,updatefiled);

                //切换阶段
                inst.setCurrent_stage(1);
                inst.setUpdate_time(new Date());
                checkBatchService.updateCheckBatchInst(inst);
                log.info("到期强制切换 switch to stage 1");
                return 1;
            }

        }

        if(inst.getCurrent_stage() == 1){//切换到打分部门反馈审核阶段

            if(period > feedback_days){
                //对于没有审批完的，或者反馈拒绝后没修改完的，统统变为状态7，打分审核通过状态，即没有提交反馈，无异议
                 Map<String,Object> updatefiled = new HashMap<String, Object>();

                updatefiled.put("problem_status",7);
                updatefiled.put("batch_id",inst.getId());
                List<Integer> statusls = new ArrayList<Integer>();
                statusls.add(2);
                statusls.add(3);
                statusls.add(4);
                updatefiled.put("w_problem_status_in",statusls);
                updateProblemGradeInfo(check_type,updatefiled);


                //切换阶段
                inst.setCurrent_stage(2);
                inst.setUpdate_time(new Date());
                checkBatchService.updateCheckBatchInst(inst);
                log.info("switch to stage 2");
                return 2;
            }
        }

        if(inst.getCurrent_stage() == 2) {//切换到批次结束

            //到达期限处理
            if (period == (review_days+1)) {
                //未处理的反馈审核
                Map<String, Object> condition = new HashMap<String, Object>();
                condition.put("batch_id", inst.getId());
                condition.put("problem_status", 5);
                List<ProblemGradeViewVo> retls = getProblemGradeViewAllWithCondition(check_type,condition);

                Map<String, Object> updatefiled = new HashMap<String, Object>();
                updatefiled.put("problem_status", 7);

                if (retls != null && retls.size() > 0) {
                    for (int i = 0; i < retls.size(); i++) {
                        ProblemFeedbackEntity fbEn = feedbackService.getProblemFeedbackEntity(retls.get(i).getId());
                        fbEn.setFeedback_result(1);
                        feedbackService.updateProblemFeedback(fbEn);
                        updatefiled.put("id", retls.get(i).getId());
                        updatefiled.put("score", fbEn.getFeedback_score());
                        updateProblemGradeInfo(check_type,updatefiled);
                    }
                }

                //切换阶段
                //inst.setCurrent_stage(3);//此处不切换阶段，完成阶段在下一个批次开始时再切换
                //inst.setUpdate_time(new Date());
                //checkBatchService.updateCheckBatchInst(inst);
                log.info("到期强制切换 switch to stage 3");
                return 3;
            }
        }
        //加分申请单独处理
        {

            //加分申请处理，部门及单位审核未完成或不通过的，按未加分申请处理，最终审核未完成的，按通过处理
            //处理加分申请
            int period_addScore = DateUtil.workDaysPeriod(inst.getStart_date(),today);
            if(period_addScore > add_score_apply_days && period_addScore < add_score_apply_days + add_score_review_days) {
                Map<String, Object> scoreAddCondition = new HashMap<String, Object>();
                scoreAddCondition.put("batch_id", inst.getId());
                int[] status_in = {0, 3, 4};
                scoreAddCondition.put("apply_status_in", status_in);
                List<ScoreAddApplyEntity> retsals = scoreAddApplyEntityMapper.selectScoreAddApply(scoreAddCondition);
                if (retsals != null && retsals.size() > 0) {
                    for (int i = 0; i < retsals.size(); i++) {
                        ScoreAddApplyEntity t = retsals.get(i);
                        t.setApply_result(0);
                        t.setApply_status(5);
                        scoreAddApplyEntityMapper.updateScoreAddApply(t);
                    }
                }
            }

            //未处理的加分申请
            int totle_period = add_score_apply_days + add_score_review_days;
            if(period_addScore > totle_period && period_addScore < totle_period + 2) {
                Map<String, Object> scoreAddCondition2 = new HashMap<String, Object>();
                scoreAddCondition2.put("batch_id", inst.getId());
                scoreAddCondition2.put("apply_status", 1);
                List<ScoreAddApplyEntity> retsals2 = scoreAddApplyEntityMapper.selectScoreAddApply(scoreAddCondition2);

                //处理加分申请
                if (retsals2 != null && retsals2.size() > 0) {
                    for (int i = 0; i < retsals2.size(); i++) {
                        ScoreAddApplyEntity t = retsals2.get(i);
                        t.setApply_result(1);
                        t.setApply_status(5);
                        scoreAddApplyEntityMapper.updateScoreAddApply(t);
                    }
                }
            }
        }


        return -1;
    }

}
